package com.sunyard.manage.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sunyard.dal.bo.PaginationBO;
import com.sunyard.dal.bo.device.TerminalWarningQueryBO;
import com.sunyard.dal.bo.device.key.KeyWarningQueryBO;
import com.sunyard.dal.bo.device.lock.LockWarningQueryBO;
import com.sunyard.dal.dto.KeyWarningQueryDTO;
import com.sunyard.dal.dto.LockWarningQueryDTO;
import com.sunyard.dal.dto.TerminalWarningQueryDTO;
import com.sunyard.dal.entity.BoxAlarm;
import com.sunyard.dal.entity.Operator;
import com.sunyard.dal.entity.Organization;
import com.sunyard.dal.entity.Terminal;
import com.sunyard.dal.mapper.BoxAlarmMapper;
import com.sunyard.dal.mapper.OperatorMapper;
import com.sunyard.dal.mapper.TerminalMapper;
import com.sunyard.manage.service.OrganizationService;
import com.sunyard.manage.service.TerminalWarningService;
import com.sunyard.utils.DateUtil;
import com.sunyard.utils.Response.BaseResult;
import com.sunyard.utils.Response.GetResult;
import com.sunyard.utils.TokenUtil;
import com.sunyard.utils.manage.DataGrid;
import com.sunyard.utils.manage.PageQuery;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import static com.sunyard.utils.DateUtil.strToDateLong;

/**
 * @author wxl
 * @date 2022-07-01 15:36
 */
@Service
@Slf4j
public class TerminalWarningServiceImpl implements TerminalWarningService {

    @Autowired
    private OrganizationService organizationService;

    @Autowired
    TerminalMapper terminalMapper;

    @Autowired
    OperatorMapper operatorMapper;

    @Autowired
    BoxAlarmMapper boxAlarmMapper;

    //终端预警超时时间
    @Value("${keyWarning.timeOut}")
    private long timeOut;


    @Override
    public BaseResult<DataGrid<TerminalWarningQueryDTO>> queryTerminalWarning(
            PaginationBO<TerminalWarningQueryBO> queryBO, HttpServletRequest request) {
        TerminalWarningQueryBO terminalWarningQueryBO = queryBO.getParams();
        log.info("设备预警查询,请求参数[" + terminalWarningQueryBO.toString() + "]");
        String type = terminalWarningQueryBO.getType();
//根据当前时间 查询网点需要的数据
        long queryTime = DateUtil.getQueryTime();
        if (!"".equals(type) && type != null) {
            if ("0".equals(type)) {
                //0-钥匙预警
                KeyWarningQueryBO keyWarningQueryBO = new KeyWarningQueryBO();
                PaginationBO<KeyWarningQueryBO> keyWarningQueryBOPaginationBO = new PaginationBO<>();
                keyWarningQueryBOPaginationBO.setPageNo(queryBO.getPageNo());
                keyWarningQueryBOPaginationBO.setPageSize(queryBO.getPageSize());
                keyWarningQueryBOPaginationBO.setMaxPageSize(queryBO.getMaxPageSize());
                keyWarningQueryBOPaginationBO.setParams(keyWarningQueryBO);
                keyWarningQueryBO.setEnd(queryTime);
                return queryKeyWarningNew(keyWarningQueryBOPaginationBO, request);
            } else if ("1".equals(type)) {
                //1-锁具预警
                LockWarningQueryBO lockWarningQueryBO = new LockWarningQueryBO();
                PaginationBO<LockWarningQueryBO> lockWarningQueryBOPaginationBO = new PaginationBO<>();
                lockWarningQueryBOPaginationBO.setPageNo(queryBO.getPageNo());
                lockWarningQueryBOPaginationBO.setPageSize(queryBO.getPageSize());
                lockWarningQueryBOPaginationBO.setMaxPageSize(queryBO.getMaxPageSize());
                lockWarningQueryBOPaginationBO.setParams(lockWarningQueryBO);
                return queryLockWarningNew(lockWarningQueryBOPaginationBO, request);
            } else if ("2".equals(type)) {
                //2-尾箱预警
                String orgId = TokenUtil.getOrgId(request.getHeader("token"));
                TerminalWarningQueryBO warningQueryBO = queryBO.getParams();
                List<String> orgIdList = new ArrayList<>();
                //获取当前机构及所有子机构
                try {
                    List<Organization> orgIds = organizationService.getOrgIds(orgId);
                    for (Organization organization : orgIds) {
                        orgIdList.add(organization.getOrgId());
                    }
                } catch (Exception e) {
                    log.error("获取当前机构及所有子机构异常", e);
                    throw new RuntimeException(e.getMessage());
                }
                PageHelper.startPage(queryBO.getPageNo(), queryBO.getPageSize());
                List<BoxAlarm> queryList = boxAlarmMapper.getBoxAlarmByPage(orgIdList);
                List<TerminalWarningQueryDTO> queryResList = new ArrayList<>();
                for (BoxAlarm boxAlarm : queryList) {
                    TerminalWarningQueryDTO queryDTO = new TerminalWarningQueryDTO();
                    queryDTO.setId(boxAlarm.getId());
                    queryDTO.setBoxId(boxAlarm.getBoxId());
                    queryDTO.setAlarmType(boxAlarm.getType());
                    queryDTO.setLockName(boxAlarm.getLockName());
                    queryDTO.setLongitude(boxAlarm.getLongitude());
                    queryDTO.setLatitude(boxAlarm.getLatitude());
                    queryDTO.setLockStatus(boxAlarm.getLockStatus());
                    queryDTO.setDoorStatus(boxAlarm.getDoorStatus());
                    queryDTO.setDescription(boxAlarm.getDescription());
                    queryDTO.setCreateTime(boxAlarm.getCreateTime());
                    queryDTO.setMissionId(boxAlarm.getMissionId());
                    Terminal terminal = terminalMapper.selectByPrimaryKey(boxAlarm.getBoxId());
                    queryDTO.setName(terminal.getName());
                    queryDTO.setLastTime(terminal.getLastTime());
                    queryResList.add(queryDTO);
                }
                DataGrid dataGrid = PageQuery.getDataGrids(queryList, queryResList);
                return GetResult.getResult(dataGrid);
            } else {
                log.error("设备预警查询请求参数非法！");
                throw new RuntimeException("设备预警查询请求参数非法！");
            }
        } else {
            log.error("设备预警查询请求参数异常！");
            throw new RuntimeException("设备预警查询请求参数异常！");
        }

    }

    @Override
    public BaseResult<DataGrid<KeyWarningQueryDTO>> queryKeyWarning(PaginationBO<KeyWarningQueryBO> queryBO, HttpServletRequest request) {
        //long timeLong = 7 * 24 * 60 * 60 * 1000;
        //String opId = TokenUtil.getOpId(request.getHeader("token"));
        String orgId = TokenUtil.getOrgId(request.getHeader("token"));
        KeyWarningQueryBO keyWarningQueryBO = queryBO.getParams();

        List<String> orgIdList = new ArrayList<>();
        //获取当前机构及所有子机构
        try {
            List<Organization> orgIds = organizationService.getOrgIds(orgId);
            for (Organization organization : orgIds) {
                orgIdList.add(organization.getOrgId());
            }
        } catch (Exception e) {
            log.error("获取当前机构及所有子机构异常", e);
            throw new RuntimeException(e.getMessage());
        }

        keyWarningQueryBO.setOrgIdList(orgIdList);
        keyWarningQueryBO.setTimeOut(timeOut);
        keyWarningQueryBO.setCurrentTime(System.currentTimeMillis());
        log.info("终端预警查询,请求参数[" + queryBO.getParams().toString() + "]");
        //设置分页信息
        //PageMethod.startPage(queryBO.getPageNo(), queryBO.getPageSize());
        PageHelper.startPage(queryBO.getPageNo(), queryBO.getPageSize());
        // 执行查询
        List<KeyWarningQueryDTO> keyWarningQueryDTOList = terminalMapper.queryKeyWarning(keyWarningQueryBO);
        // 取分页信息
        PageInfo<KeyWarningQueryDTO> pageInfo = new PageInfo<>(keyWarningQueryDTOList);
        // 设置返回结果
        DataGrid<KeyWarningQueryDTO> dataGrid = new DataGrid<>();
        long total = pageInfo.getTotal();
        dataGrid.setTotal(new Long(total).intValue());
        dataGrid.setPageNum(queryBO.getPageNo());
        dataGrid.setRows(keyWarningQueryDTOList);
        return GetResult.getResult(dataGrid);
    }

    @Override
    public BaseResult<DataGrid<LockWarningQueryDTO>> queryLockWarning(PaginationBO<LockWarningQueryBO> queryBO, HttpServletRequest request) {
        String orgId = TokenUtil.getOrgId(request.getHeader("token"));
        LockWarningQueryBO lockWarningQueryBO = queryBO.getParams();
        List<String> orgIdList = new ArrayList<>();
        //获取当前机构及所有子机构
        try {
            List<Organization> orgIds = organizationService.getOrgIds(orgId);
            for (Organization organization : orgIds) {
                orgIdList.add(organization.getOrgId());
            }
        } catch (Exception e) {
            log.error("获取当前机构及所有子机构异常", e);
            throw new RuntimeException(e.getMessage());
        }

        long start, end = System.currentTimeMillis();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        start = calendar.getTime().getTime();

        lockWarningQueryBO.setOrgIdList(orgIdList);
        lockWarningQueryBO.setStart(start);
        lockWarningQueryBO.setEnd(end);
        log.info("锁具预警查询,请求参数[" + queryBO.getParams().toString() + "]");

        //设置分页信息
        //PageMethod.startPage(queryBO.getPageNo(), queryBO.getPageSize());
        PageHelper.startPage(queryBO.getPageNo(), queryBO.getPageSize());
        // 执行查询
        List<LockWarningQueryDTO> lockWarningQueryDTOList = terminalMapper.queryLockWarning(lockWarningQueryBO);
        // 取分页信息
        PageInfo<LockWarningQueryDTO> pageInfo = new PageInfo<>(lockWarningQueryDTOList);
        // 设置返回结果
        DataGrid<LockWarningQueryDTO> dataGrid = new DataGrid<>();
        long total = pageInfo.getTotal();
        dataGrid.setTotal(new Long(total).intValue());
        dataGrid.setPageNum(queryBO.getPageNo());
        dataGrid.setRows(lockWarningQueryDTOList);
        return GetResult.getResult(dataGrid);
    }

    @Override
    public BaseResult<DataGrid<TerminalWarningQueryDTO>> queryKeyWarningNew(PaginationBO<KeyWarningQueryBO> queryBO, HttpServletRequest request) {
        //long timeLong = 7 * 24 * 60 * 60 * 1000;
        //String opId = TokenUtil.getOpId(request.getHeader("token"));
        String orgId = TokenUtil.getOrgId(request.getHeader("token"));
        KeyWarningQueryBO keyWarningQueryBO = queryBO.getParams();

        List<String> orgIdList = new ArrayList<>();
        //获取当前机构及所有子机构
        try {
            List<Organization> orgIds = organizationService.getOrgIds(orgId);
            for (Organization organization : orgIds) {
                orgIdList.add(organization.getOrgId());
            }
        } catch (Exception e) {
            log.error("获取当前机构及所有子机构异常", e);
            throw new RuntimeException(e.getMessage());
        }

        keyWarningQueryBO.setOrgIdList(orgIdList);
        // timeOut = 86400000L;
        timeOut = 15 * 24 * 60 * 60 * 1000L;
        keyWarningQueryBO.setTimeOut(timeOut);
        // 当天23:59:59:999 最后时间
        keyWarningQueryBO.setCurrentTime(DateUtil.getEndOfTodDay().getTime());
        long queryTime = DateUtil.getQueryTime();
        keyWarningQueryBO.setEnd(queryTime);
        log.info("终端预警查询,请求参数[" + queryBO.getParams().toString() + "]");
        //设置分页信息
        //PageMethod.startPage(queryBO.getPageNo(), queryBO.getPageSize());
        PageHelper.startPage(queryBO.getPageNo(), queryBO.getPageSize());
        // 执行查询
        List<TerminalWarningQueryDTO> terminalWarningQueryDTOList = terminalMapper.queryKeyWarningNew(keyWarningQueryBO);
        for (TerminalWarningQueryDTO queryDTO: terminalWarningQueryDTOList) {
            Operator operator = operatorMapper.getOperatorByOpId(queryDTO.getCreateUser());
            if(null!=operator){
                queryDTO.setCreateUser(operator.getOpName());
                queryDTO.setCreateUserRealName(operator.getOpRealname());
            }
        }
        // for (TerminalWarningQueryDTO terminalWarningQueryDTO: terminalWarningQueryDTOList) {
        //     if (StringUtils.isBlank(terminalWarningQueryDTO.getLastTime())){
        //         terminalWarningQueryDTO.setLastTime("从未上传");
        //     }
        // }
        // 取分页信息
        PageInfo<TerminalWarningQueryDTO> pageInfo = new PageInfo<>(terminalWarningQueryDTOList);
        // 设置返回结果
        DataGrid<TerminalWarningQueryDTO> dataGrid = new DataGrid<>();
        long total = pageInfo.getTotal();
        dataGrid.setTotal(new Long(total).intValue());
        dataGrid.setPageNum(queryBO.getPageNo());
        dataGrid.setRows(terminalWarningQueryDTOList);
        return GetResult.getResult(dataGrid);
    }

    @Override
    public BaseResult<DataGrid<TerminalWarningQueryDTO>> queryLockWarningNew(PaginationBO<LockWarningQueryBO> queryBO, HttpServletRequest request) {
        String orgId = TokenUtil.getOrgId(request.getHeader("token"));
        LockWarningQueryBO lockWarningQueryBO = queryBO.getParams();
        List<String> orgIdList = new ArrayList<>();
        //获取当前机构及所有子机构
        try {
            List<Organization> orgIds = organizationService.getOrgIds(orgId);
            for (Organization organization : orgIds) {
                orgIdList.add(organization.getOrgId());
            }
        } catch (Exception e) {
            log.error("获取当前机构及所有子机构异常", e);
            throw new RuntimeException(e.getMessage());
        }

        long start, end = System.currentTimeMillis();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        start = calendar.getTime().getTime();

        lockWarningQueryBO.setOrgIdList(orgIdList);
   /*     lockWarningQueryBO.setStart(start);
        lockWarningQueryBO.setEnd(end);*/
        //根据当前时间 查询网点需要的数据
        long queryTime = DateUtil.getQueryTime();
        lockWarningQueryBO.setEnd(queryTime);
        log.info("锁具预警查询,请求参数[" + queryBO.getParams().toString() + "]");

        //设置分页信息
        //PageMethod.startPage(queryBO.getPageNo(), queryBO.getPageSize());
        PageHelper.startPage(queryBO.getPageNo(), queryBO.getPageSize());
        // 执行查询
        List<TerminalWarningQueryDTO> terminalWarningQueryDTOList = terminalMapper.queryLockWarningNew(lockWarningQueryBO);
        for (TerminalWarningQueryDTO queryDTO: terminalWarningQueryDTOList) {
            Operator operator = operatorMapper.getOperatorByOpId(queryDTO.getCreateUser());
            if(null!=operator){
                queryDTO.setCreateUser(operator.getOpName());
                queryDTO.setCreateUserRealName(operator.getOpRealname());
            }
            if (StringUtils.isNotBlank(queryDTO.getOpenLockTime())){
                queryDTO.setOpenLockTime(strToDateLong(queryDTO.getOpenLockTime()));
            }
        }
        // 取分页信息
        PageInfo<TerminalWarningQueryDTO> pageInfo = new PageInfo<>(terminalWarningQueryDTOList);
        // 设置返回结果
        DataGrid<TerminalWarningQueryDTO> dataGrid = new DataGrid<>();
        long total = pageInfo.getTotal();
        dataGrid.setTotal(new Long(total).intValue());
        dataGrid.setPageNum(queryBO.getPageNo());
        dataGrid.setRows(terminalWarningQueryDTOList);
        return GetResult.getResult(dataGrid);
    }

    public static void main(String[] args) {
        String s = String.valueOf(System.currentTimeMillis());
        System.out.println(s);
    }

 /*   @Override
    public BaseResult<DataGrid<OperatorLog>> queryTailBoxWarning(PaginationBO<NonWorkTimeQueryBo> queryBO) {
        log.info("尾箱预警查询,请求参数["+queryBO.getParams().toString()+"]");
        //设置分页信息
        //PageMethod.startPage(queryBO.getPageNo(), queryBO.getPageSize());
        PageHelper.startPage(queryBO.getPageNo(), queryBO.getPageSize());
        // 执行查询
        List<OperatorLog> operatorLogList = terminalWarningMapper.queryTailBoxWarning(queryBO.getParams());
        // 取分页信息
        PageInfo<OperatorLog> pageInfo = new PageInfo<>(operatorLogList);
        // 设置返回结果
        DataGrid<OperatorLog> dataGrid = new DataGrid<>();
        long total = pageInfo.getTotal();
        dataGrid.setTotal(new Long(total).intValue());
        dataGrid.setPageNum(queryBO.getPageNo());
        dataGrid.setRows(operatorLogList);
        return GetResult.getResult(dataGrid);
    }*/

}